package cj.web.marry.controllers;

import java.net.URLEncoder;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;

import cj.utils.Constants;
import cj.web.BaseController;
import cj.web.mall.dao.UserDAO;
import cj.web.marry.constants.EducationEnum;
import cj.web.marry.constants.MemberComTypeEnum;
import cj.web.marry.constants.SalaryEnum;
import cj.web.marry.constants.XQYHStatusEnum;
import cj.web.marry.dao.FollowDAO;
import cj.web.marry.dao.XQCmpYHDAO;
import cj.web.marry.utils.IdcardUtils;

@Path("xqCmpYH")
public class XQCmpYHController extends BaseController{

	@Autowired
	private XQCmpYHDAO xqCmpYHDAO;
	@Autowired
	private UserDAO userDao;
	@Autowired
	private FollowDAO followDao;
	
	@Get("cmpMember")
	public String cmpMember(Model model, HttpServletRequest request) throws Exception{
		if( isLogin(request) ){
			
			String phone = getCookieValueByName(request, "phone");
			int buyerId = userDao.getBuyerId(phone);
			int isExist = userDao.isExistMemberDetailCmp(buyerId,MemberComTypeEnum.NUM_1.getValue());
			
			if(isExist==0){
				return "r:../xqLoginCmp/fail";
			}
			
			Map<String, String> config = getConfigSign(request);
			model.add("Config",config);
			
			model.add("Title", "长江婚典商城-您的专属婚品");
			model.add("Desc", "只为您专属打造");
			model.add("LinkURL", oauth_start+request.getScheme() +"://" + request.getServerName() + "/pubAct/homeCode"+oauth_end);
		}else{
			String retPg = URLEncoder.encode("xqCmpYH/cmpMember", "utf-8");
			return "r:../xqLoginCmp/login?returnPage=" + retPg;
		}
		model.add("EducationEnum",EnumSet.allOf(EducationEnum.class));
        model.add("SalaryEnum",EnumSet.allOf(SalaryEnum.class));
		return "/views/marry/meet/member/memberRecommend.vm";
	}
	
	@Get("cmpMemberlis")
	public String cmpMemberlis(Model model,@Param("education") String education,@Param("agePicker") String agePicker,
			@Param("salaryPicker") String salaryPicker,@Param("profession") String profession,@Param("province") String province,
			@Param("dataOrder") String dataOrder,@Param("start") int start,@Param("length") int length, HttpServletRequest request) throws Exception{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		String phone = getCookieValueByName(request, "phone");
		int buyerId = userDao.getBuyerId(phone);
		
		List<Map> userls = userDao.getMemberDetailByUserId(buyerId);
		int sex = 1;
		if(userls!=null && userls.size()>0){
			sex = Integer.parseInt(userls.get(0).get("sex").toString());
		}
		
		//education 学历
				education =education.equals("不限")?"":education;
				//profession 职业
				int money = salaryPicker.equals("不限")?-1:SalaryEnum.getValue(salaryPicker);//月薪
				String area="";
				String city="";
				if(!province.equals("")){
					area=province.split(" ")[2];//区
					city=province.split(" ")[1];//市
					province=province.split(" ")[0];//省
				}
				agePicker =agePicker.equals("不限")?"":agePicker;
				//dataOrder 0最新推荐	1热度降序	2年龄升序	3年龄降序
				
				List<Map> gamels = xqCmpYHDAO.queryMemberDetailLis(MemberComTypeEnum.NUM_1.getValue(),
						start*length,length,buyerId,sex, education, profession, money, area, city,
			    		 province, dataOrder,agePicker);
		
		for(Map rep:gamels){
			int objectUserId = Integer.parseInt(rep.get("userId").toString());
			
			int count = xqCmpYHDAO.queryCmpYHSize(buyerId, objectUserId, String.valueOf(XQYHStatusEnum.doing.getValue()));
			if(count>0){
				//已约
				rep.put("flag", true);
			}else{
				//可以约
				rep.put("flag", false);
			}
			
			int followCount = followDao.querySizeByUserId(buyerId, objectUserId);
			if(followCount>0){
				//已关注
				rep.put("followFlag", true);
			}else{
				//未关注
				rep.put("followFlag", false);
			}
			rep.put("educationName", EducationEnum.getName(Integer.valueOf(rep.get("education").toString())));
		}
		
//		int totalCount = xqCmpYHDAO.queryMemberDetailLisSize(MemberComTypeEnum.NUM_1.getValue(),buyerId,sex);
		//分页计算
//		Page p= new Page<Map>(0, length, gamels, totalCount);
		jo.put("list", gamels);
//		jo.put("repsize", p.getTotalPages());
//		jo.put("totalCount", totalCount);
		return "@"+jo.toString();
	}
	
	/**
	 * 约会申请
	 * @param model
	 * @param objectUserId
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Get("apply")
	public String apply(Model model, @Param("objectUserId") int objectUserId, HttpServletRequest request) throws Exception{
		
		List<Map> obj = userDao.getMemberDetailForUC(objectUserId);
		
		obj.get(0).put("age", IdcardUtils.getAgeByIdCard(obj.get(0).get("identityCard").toString()));
		
		model.add("obj", obj.get(0));
		model.add("objectUserId", objectUserId);
		return "/views/marry/meet/member/datingApplication.vm";
	}
	
	/**
	 * 保存约会申请
	 * @param model
	 * @param objectUserId
	 * @param appointDate
	 * @param address
	 * @param descs
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Post("saveApply")
	public synchronized String saveApply(Model model, @Param("objectUserId") int objectUserId, @Param("appointDate") String appointDate, 
			@Param("address") String address, @Param("descs") String descs, HttpServletRequest request) throws Exception{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		String phone = getCookieValueByName(request, "phone");
		int buyerId = userDao.getBuyerId(phone);
		
		String yhStatus = String.valueOf(XQYHStatusEnum.doing.getValue());
		
		try {
			int count = xqCmpYHDAO.queryCmpYHSize(buyerId, objectUserId, yhStatus);
			if(count==0){
				//保存
				xqCmpYHDAO.create(buyerId, objectUserId, appointDate, address, descs, XQYHStatusEnum.doing.getValue(), phone);
				//添加数量
				xqCmpYHDAO.updateFollowCountAdd(objectUserId);
			}else{
				jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	/**
	 * 约会申请详情
	 * @param model
	 * @param objectUserId
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Get("applyDetail")
	public String applyDetail(Model model, @Param("id") int id, HttpServletRequest request) throws Exception{

		List<Map> replis = xqCmpYHDAO.queryCmpYHById(id);
		model.add("yhObj", replis.get(0));
		
		List<Map> obj = userDao.getMemberDetailForUC(
				Integer.parseInt(replis.get(0).get("objectUserId").toString()));
		obj.get(0).put("age", IdcardUtils.getAgeByIdCard(obj.get(0).get("identityCard").toString()));
		model.add("obj", obj.get(0));
		
		return "/views/marry/meet/member/datingDetail.vm";
	}
	
	/**
	 * 关注
	 * @param model
	 * @param objectUserId
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Get("follow")
	public synchronized String follow(Model model,@Param("objectUserId") int objectUserId, HttpServletRequest request) throws Exception{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		String phone = getCookieValueByName(request, "phone");
		int buyerId = userDao.getBuyerId(phone);
		try {
			int count = followDao.querySizeByUserId(buyerId, objectUserId);
			if(count==0){
				jo.put("returnCode", Constants.returnObj.returnCode.code_2);
				followDao.create(buyerId, objectUserId);
				xqCmpYHDAO.updateFollowCountAdd(objectUserId);
			}else{
				jo.put("returnCode", Constants.returnObj.returnCode.code_1);
				followDao.deleteById(buyerId, objectUserId);
				xqCmpYHDAO.updateFollowCountMinus(objectUserId);
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
}